import axios from "axios";
import { AxiosError, AxiosResponse } from "axios";
import { handleRequestError, retryWithRefreshToken } from "./errorHandler";
import { defaultToastHandler } from "./toastHandler";
import { RequestConfig } from "./types";

const axiosInstance = axios.create({
  baseURL: "/api",
  timeout: 10000,
});

axiosInstance.interceptors.request.use(
  (config) => {
    // const reqConfig = config as RequestConfig<any, any, any>;
    // const authHeader = handleTokenAuthorization(reqConfig.ignoreAuth ?? false);
    // if (authHeader) {
    //   config.headers["Authorization"] = authHeader;
    // }
    return config;
  },
  (error) => Promise.reject(error)
);

axiosInstance.interceptors.response.use(
  (response) => {
    if (response.data.success) {
      return response.data;
    } else {
      defaultToastHandler.showToast(response.data.errorMessage || "请求失败");
      return Promise.reject(response.data);
    }
  },
  async (error) => {
    // // 请求失败时的错误处理
    // const { config } = error;
    // const reqConfig = config as RequestConfig<any, any, any>;
    // // 统一处理错误，并执行重试逻辑
    // const responseError = await handleRequestError(error, reqConfig!, 0, 3);

    // // 根据配置抛出错误或返回
    // if (reqConfig?.throwError) {
    //   throw new Error(responseError.errorMessage);
    // }

    return Promise.reject(error);
  }
);

export default axiosInstance;
